package com.alvin.demo.common.handler;

import com.alvin.demo.common.pojo.Result;
import com.alvin.demo.utils.RequestUtils;
import com.alvin.demo.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(AccessDeniedException.class)
    public String handleAccessDeniedException(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 这里可以构造返回给客户端的错误信息 403
        if (RequestUtils.isStandardUrlRequest(request)){
            System.out.println(RequestUtils.isAjaxRequest(request));
            return "redirect:/error/403.html";
        }else {
            Result result = Result.error( 403 ,"无权访问该接口，403！！");
            ResponseUtils.out(response, result);
            return null ;
        }
    }


    @ExceptionHandler(NoHandlerFoundException.class)
    public String handleNotFound(
            HttpServletRequest request,
            HttpServletResponse response,
            NoHandlerFoundException ex) throws IOException {
        if (RequestUtils.isStandardUrlRequest(request)){
            log.error("请求路径不存在：{}", request.getRequestURI());
            return "redirect:/error/404.html";
        }else{
            Result result = Result.error( 404 ,"访问的接口不存在，404！！");
            ResponseUtils.out(response, result);
            return null ;
        }
    }

}